package com.autumn.validation;

import java.util.Set;

import javax.validation.Configuration;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.autumn.util.ExceptionUtils;

/**
 * 验证帮助
 * 
 * @author 老码农
 *
 *         2018-01-11 16:54:23
 */
public class ValidationUtils {	

	/**
	 * 验证对象
	 * 
	 * @param obj
	 * @return
	 *
	 */
	public static <T> void validation(T obj) {
		ExceptionUtils.checkNotNull(obj, "obj");
		ValidatorFactory factory = null;
		try {
			Configuration<?> config = Validation.byDefaultProvider().configure();
			factory = config.buildValidatorFactory();
			Validator validator = factory.getValidator();
			Set<ConstraintViolation<T>> violations = validator.validate(obj);
			if (violations.size() > 0) {
				violations.stream().forEach(s -> ExceptionUtils.throwValidationException(s.getMessage()));
			}
		} finally {
			if (factory != null) {
				factory.close();
			}
		}
	}
}
